package com.mobilepay.moneypig.model.activity.mine;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseActivity;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.model.dialog.SaiXuanDialog;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.home.OrderData;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.utils.acache.ACache;
import com.mobilepay.moneypig.view.DividerLine;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xlm on 2017/7/29 0029
 */

public class OrderActivity extends BaseActivity {

    private static final String TAG = "OrderActivity";
    private RecyclerView mOrderRecycle;
    private SmartRefreshLayout smartRefreshLayout;
    private OrderAdapter mOrderAdapter;
    private RelativeLayout mRelativeBack;
    private RelativeLayout mRelativeSX;
    private TextView mTextOrderType;
    private static List<OrderData.DataBeanX.DataBean> mNoteList;
    private int pagesize = 10;
    private int pagenum = 1;
    private int totalPage = -1;

    private static final int MODE_QUERY = 1;
    private static final int MODE_REFRESH = 2;
    private static final int MODE_MORE = 3;
    private static final int MODE_SX = 4;

    private static int CURRENT_MODE = MODE_QUERY;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_order);
    }

    @Override
    protected void initViews() {
        mOrderRecycle = (RecyclerView) findViewById(R.id.order_recycle);
        smartRefreshLayout = (SmartRefreshLayout) findViewById(R.id.order_refresh);
        mRelativeBack = (RelativeLayout) findViewById(R.id.order_back);
        mRelativeSX = (RelativeLayout) findViewById(R.id.order_sx);
        mTextOrderType = (TextView) findViewById(R.id.order_type);
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        setmNotesAdapter();
        getOrderData();
    }

    @Override
    protected void onSetListener() {
        mRelativeBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mOrderAdapter.setOnOrderClickListener(new OrderAdapter.OnOrderClickListener() {
            @Override
            public void onClick(int id, int uid) {

            }
        });
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pagenum = 1;
                CURRENT_MODE = MODE_REFRESH;
                getOrderData();
            }
        });
        smartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (totalPage != -1 && pagenum < totalPage) {
                    pagenum++;
                    CURRENT_MODE = MODE_MORE;
                    getOrderData();
                } else {
                    smartRefreshLayout.setEnableLoadmore(false);
                }
            }
        });
        mRelativeSX.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showOrderDialog();
            }
        });

    }

    private SaiXuanDialog saiXuanDialog;
    private String sceneId = "";

    private void showOrderDialog() {
        if (saiXuanDialog == null) {
            saiXuanDialog = new SaiXuanDialog(getThis());
        }
        saiXuanDialog.setCancelable(true);
        saiXuanDialog.show();
        saiXuanDialog.setListener(new SaiXuanDialog.Listener() {
            @Override
            public void clickLable(String id, String name) {
                super.clickLable(id, name);
                mTextOrderType.setText(name);
                CURRENT_MODE = MODE_SX;
                sceneId = id;
                if ("0".equals(id)) {
                    sceneId = "";
                    mTextOrderType.setText("全部订单");
                }
                pagenum = 1;
                saiXuanDialog.dismiss();
                getOrderData();
            }
        });
    }

    private void getOrderData() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.getOrderList);
        param.add("uid", String.valueOf(App.getApp().getUserInfo().getData().getUid()));
        param.add("scene_id", sceneId);
        param.add("status", "");
        param.add("page_size", String.valueOf(pagesize));
        param.add("current_page", String.valueOf(pagenum));
        param.add("sign", param.getMd5String());
        showProgress("加载中");
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                    String jsonString = ACache.get(App.getApp()).getAsString(NetConfig.getOrderList);
                    if (!CommonUtil.isEmpty(jsonString)) {
                        mNoteList.clear();
                        setOrderData(jsonString, false);
                    }
                }

                if (totalPage != -1 && pagenum < totalPage) {
                    smartRefreshLayout.setEnableLoadmore(true);
                } else {
                    smartRefreshLayout.setEnableLoadmore(false);
                }

                switch (CURRENT_MODE) {
                    case MODE_QUERY:
                        break;
                    case MODE_REFRESH:
                        smartRefreshLayout.finishRefresh(false);
                        break;
                    case MODE_MORE:
                        smartRefreshLayout.finishLoadmore(false);
                        break;
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissProgress();
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (responseResult.getStatus() == 1) {
                        setOrderData(string, true);
                    } else {
                        showToastShort(responseResult.getInfo());
                        smartRefreshLayout.setEnableLoadmore(false);
                    }
                } else {
                    smartRefreshLayout.setEnableLoadmore(false);
                }
                switch (CURRENT_MODE) {
                    case MODE_QUERY:
                        break;
                    case MODE_REFRESH:
                        smartRefreshLayout.finishRefresh(true);
                        break;
                    case MODE_MORE:
                        smartRefreshLayout.finishLoadmore(true);
                        break;
                }
                if (totalPage != -1 && pagenum < totalPage)

                {
                    smartRefreshLayout.setEnableLoadmore(true);
                } else

                {
                    smartRefreshLayout.setEnableLoadmore(false);
                }
            }
        });
    }

    private void setOrderData(String string, boolean save) {
        OrderData notesData = GsonUtil.GsonToBean(string, OrderData.class);
        totalPage = notesData.getData().getLast_page();
        List<OrderData.DataBeanX.DataBean> dataBeanList = notesData.getData().getData();
        if (CURRENT_MODE != MODE_MORE) {
            mNoteList.clear();
        }
        if (dataBeanList.size() != 0) {
            mNoteList.addAll(dataBeanList);
        } else {
            smartRefreshLayout.setEnableLoadmore(false);
        }
        mOrderAdapter.setNotesData(mNoteList);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mOrderAdapter.notifyDataSetChanged();
            }
        });

        if (save) {
            try {
                String json = GsonUtil.GsonString(mNoteList);
                JSONObject jsonObject = new JSONObject(string);
                JSONObject jsonObject1 = jsonObject.optJSONObject("data");
                JSONArray jsonArray = new JSONArray(json);
                jsonObject1.put("data", jsonArray);
                ACache.get(App.getApp()).put(NetConfig.getOrderList, jsonObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void setmNotesAdapter() {
        mNoteList = new ArrayList<>();
        mOrderAdapter = new OrderAdapter(getThis());
        mOrderAdapter.setNotesData(mNoteList);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getThis(), LinearLayoutManager.VERTICAL, false);
        DividerLine dividerLine = new DividerLine(DividerLine.VERTICAL);
        dividerLine.setSize(25);
        dividerLine.setColor(getResources().getColor(R.color.divider_line));
//        mOrderRecycle.addItemDecoration(dividerLine);
        mOrderRecycle.setLayoutManager(layoutManager);
        mOrderRecycle.setAdapter(mOrderAdapter);
    }

    private static class OrderAdapter extends RecyclerView.Adapter<OrdeViewHolder> {
        private List<OrderData.DataBeanX.DataBean> beanList;
        private LayoutInflater inflater;

        public OrderAdapter(Context context) {
            this.inflater = LayoutInflater.from(context);
        }

        public void setNotesData(List<OrderData.DataBeanX.DataBean> dataBeanList) {
            this.beanList = dataBeanList;
        }

        @Override
        public OrdeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new OrdeViewHolder(inflater.inflate(R.layout.item_order_list, parent, false));
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(OrdeViewHolder holder, int position) {
            final OrderData.DataBeanX.DataBean bean = beanList.get(position);
            int pay_type = bean.getPay_type();
            if (pay_type == 0) {
                holder.order_ispay.setText("未完成");
            } else {
                holder.order_ispay.setText("已支付");
            }
            holder.order_num.setText(bean.getOut_trade_no());
            holder.order_amount.setText(bean.getPay_amount());
            holder.order_time.setText(CommonUtil.formatDate(bean.getCreate_time() * 1000, "yyyy-MM-dd HH:mm:ss"));
//            int pay_type = bean.getPay_type();
//            if (pay_type == 0) {
//                holder.order_ispay.setText(bean.getBody());
//                holder.order_num.setText(bean.getOut_trade_no());
//                holder.order_amount.setText("未完成");
//                holder.order_type.setText("未完成");
//
//                holder.order_time.setText("未完成");
//            } else {
//                holder.order_ispay.setText(bean.getBody());
//                holder.order_num.setText(bean.getOut_trade_no());
//                holder.order_amount.setText(bean.getPay_amount());
//                if (pay_type == 1) {
//                    holder.order_type.setText("支付宝扫码");
//                } else if (pay_type == 2) {
//                    holder.order_type.setText("微信扫码");
//                } else if (pay_type == 3) {
//                    holder.order_type.setText("银行卡快捷");
//                } else if (pay_type == 4) {
//                    holder.order_type.setText("app支付");
//                }
//                holder.order_time.setText(CommonUtil.formatDate(bean.getCreate_time() * 1000, "yyyy-MM-dd HH:mm:ss"));
//                holder.order_order_time.setText(CommonUtil.formatDate(bean.getCreate_time() * 1000, "yyyy-MM-dd HH:mm:ss"));
//            }
        }

        @Override
        public int getItemCount() {
            return beanList.size();
        }

        public void setOnOrderClickListener(OnOrderClickListener listener) {
            this.onOrderClickListener = listener;
        }

        private OnOrderClickListener onOrderClickListener;

        public interface OnOrderClickListener {
            void onClick(int id, int uid);
        }
    }

    static class OrdeViewHolder extends RecyclerView.ViewHolder {
        private TextView order_ispay;
        private TextView order_num;
        private TextView order_amount;
        private TextView order_type;
        private TextView order_time;
        private TextView order_order_time;

        public OrdeViewHolder(View itemView) {
            super(itemView);
            order_ispay = (TextView) itemView.findViewById(R.id.order_ispay);
            order_num = (TextView) itemView.findViewById(R.id.order_num);
            order_amount = (TextView) itemView.findViewById(R.id.order_amount);
            order_type = (TextView) itemView.findViewById(R.id.order_type);
            order_time = (TextView) itemView.findViewById(R.id.order_time);
            order_order_time = (TextView) itemView.findViewById(R.id.order_order_time);
        }
    }
}
